//该js用于初始化前端页面

const modelPath = './static/models/machine.glb'

import * as utils from './utils.js'

utils.init(modelPath)

//记录日志
let info = document.querySelector('#info')
function log(text, level){
    info.innerHTML = '<p class="info-' + level + '">' + text + '</p>' + info.innerHTML
}

//worker线程运行消息服务
const MESSAGE_SERVICE = new Worker('./static/js/reportReceive.js')
MESSAGE_SERVICE.postMessage(window.location.host + window.location.pathname)
MESSAGE_SERVICE.onmessage = e => {
    let arr = utils.safeParseJSON(e.data)
    if (arr !== false) {
        utils.analysisReport(arr)
    } else {
        log('接收到未知消息', 'warn')
    }
}

//菜单初始化
let titles = document.querySelectorAll('.title')
for (let i = 0; i < titles.length; i++) {
    titles[i].addEventListener('click', e => {
        e.target.parentNode.classList.toggle('closed')
    })
}

let ranges = document.querySelectorAll('input[type=range]')
for (let i = 0; i < ranges.length; i++) {
    ranges[i].addEventListener('mousemove', e => {
        document.querySelector('label[for=' + e.target.id + ']').innerHTML = e.target.value
    })
}

//触发推杆动画
let hold_range = document.querySelector('#hold-range')
let pushers = document.querySelectorAll('button.push')
for (let i = 0; i < pushers.length; i++) {
    pushers[i].addEventListener('click', e => {
        e.target.setAttribute('disabled', '')
        MESSAGE_SERVICE.postMessage([3, parseInt(e.target.getAttribute('data-id')), 1, hold_range.value * 10, 0, 0, 0, 0])
    })
}

//触发传送带动画
let short_speed = document.querySelector('#belt-s-range')
let long_speed = document.querySelector('#belt-l-range')

document.querySelector('#belt-s').onclick = e => {
    e.target.setAttribute('disabled', '')
    if (e.target.getAttribute('data-roll') === 'true') {
        MESSAGE_SERVICE.postMessage([2, 1, 0, 0, 0, 0, 0, 0])
    } else {
        MESSAGE_SERVICE.postMessage([1, 1, parseInt(short_speed.value), 0, 0, 0, 0, 0])
    }
}
document.querySelector('#belt-l').onclick = e => {
    e.target.setAttribute('disabled', '')
    if (e.target.getAttribute('data-roll') === 'true') {
        MESSAGE_SERVICE.postMessage([2, 2, 0, 0, 0, 0, 0, 0])
    } else {
        MESSAGE_SERVICE.postMessage([1, 2, parseInt(long_speed.value), 0, 0, 0, 0, 0])
    }
}